import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from '@/api';
import { setToken, getToken, removeToken } from '@/utils/token'
//登录与注册模块
const state = {
    code: '',
    token: getToken(),
    userInfo: {}
};
const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    USERLOGIN(state, token) {
        state.token = token;
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo;
    },
    //清除本地数据
    CLEAR(state) {
        //帮仓库中先关用户信息清空
        state.token = '';
        state.userInfo = {};
        //本地存储数据清空
        removeToken();
    }
};
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        //获取验证码的接口  返回了验证码  正常情况是发到手机
        let result = await reqGetCode(phone);
        if (result.code == 200) {
            commit('GETCODE', result.data);
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    },
    //登录业务
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data);
        // console.log(result);
        //服务器下发token,用户唯一标识符
        if (result.code == 200) {
            //用户登录成功并获取到token
            commit('USERLOGIN', result.data.token);
            //持久化存储token
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    },
    //获取用户信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo();
        if (result.code == 200) {
            commit('GETUSERINFO', result.data);
            return 'ok'
        } else {
            // Promise.reject(new Error(result.message))
        }
    },
    //退出登录
    async userLogout({ commit }) {
        //向服务器发请求，通知服务器清除token
        let result = await reqLogout();
        //action里面不能操作state.需要提交mutations
        if (result.code == 200) {
            commit('CLEAR');
            return 'ok'
        } else {
            Promise.reject(new Error('fail'))
        }
    }
};
const getters = {};
export default {
    state,
    mutations,
    actions,
    getters
}